package com.ktgj.pay.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class HttpHelper {
	public static String getBodyString(HttpServletRequest request){
		StringBuilder sb = new StringBuilder();
		InputStream inputStream = null;
		BufferedReader reader = null;
		String decode = null;
		try {
			inputStream = request.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream,Charset.forName("UTF-8")));
			String line = "";
			while((line = reader.readLine()) != null){
				sb.append(line);
			}
			decode = URLDecoder.decode(sb.toString(), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		Map<String, Object> map = new HashMap<>();
		String[] split = decode.split("&");
		for (String str : split) {
			String[] strings = str.split("=");
			map.put(strings[0], strings[1]);
		}
		String json = JSON.toJSONString(map);
		return json;
		
	}
}